import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
    Condition可以很方便的实现进程之间的精准唤醒
 */
public class ConditionDemo {
    public static void main(String[] args) {
        Print print=new Print();
        new Thread(()->{
            while (true){
                print.print1();
            }
        },"A").start();
        new Thread(()->{
            while (true){
                print.print2();
            }
        },"B").start();
        new Thread(()->{
            while (true){
                print.print3();
            }
        },"C").start();
    }
}
class Print{
    //标志位
    private int number=1;
    private Lock lock=new ReentrantLock();
    private Condition c1=lock.newCondition();
    private Condition c2=lock.newCondition();
    private Condition c3=lock.newCondition();

    public void print1(){
        lock.lock();
        try {
            while (number!=1){
                c1.await();
            }
            System.out.println(Thread.currentThread().getName());
            number=2;
            c2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void print2(){
        lock.lock();
        try {
            while (number!=2){
                c2.await();
            }
            System.out.println(Thread.currentThread().getName());
            number=3;
            c3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void print3(){
        lock.lock();
        try {
            while (number!=3){
                c3.await();
            }
            System.out.println(Thread.currentThread().getName());
            number=1;
            c1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
